<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card class="box-card">
      <div class="query-card">
        <!-- <el-row type="flex" align="middle">
        <el-col :span="12">-->
        <div class="grid-content bg-purple search">
          <el-form ref="query" :model="query" label-width="100px">
            <el-form-item style="margin-bottom:0px" label="赏级名称">
              <i slot="label" class="el-icon-search" style="font-size:20px"></i>
              <el-input v-model="query.keywords" placeholder="请输入赏级名称"></el-input>
            </el-form-item>
            <el-form-item style="margin-bottom:0px" label="分类">
              <el-select v-model="query.type" placeholder="请选择赏级分类">
                <el-option label="全部" value="0"></el-option>
                <el-option label="天选之人" value="1"></el-option>
                <el-option label="无限盲盒" value="2"></el-option>
                <el-option label="寻宝" value="3"></el-option>
                <el-option label="能量球" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <!-- </el-col> -->
        <!-- <el-col :span="12"> -->
        <div class="grid-content bg-purple-light">
          <el-button type="primary" @click="queryAsk">查询</el-button>
          <el-button @click="queryReset">重置</el-button>
        </div>
        <!-- </el-col>
        </el-row>-->
      </div>
    </el-card>

    <!-- 表格 -->
    <el-card class="box-card">
      <el-button type="primary" style="margin-bottom:20px" @click="addList">添加</el-button>
      <el-table
        :data="tableData"
        :header-cell-style="{background:'#eee'}"
        border
        v-loading="loading"
        style="width: 100%;margin-bottom: 20px;"
      >
        <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>
        <el-table-column align="center" prop="name" label="赏级名称"></el-table-column>
        <el-table-column align="center" label="赏级图片">
          <template slot-scope="scope">
            <el-popover placement="top-start" title trigger="hover">
              <img :src="scope.row.img" alt style="max-width:150px" />
              <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
              <el-avatar
                slot="reference"
                shape="square"
                :size="50"
                fit="scale-down"
                :src="scope.row.img"
              ></el-avatar>
              <!-- <img
                slot="reference"
                :src="scope.row.img"
                style="width: 60px;height: 60px"
              />-->
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column align="center" label="盲盒类型">
          <template slot-scope="scope">
            <div v-if="scope.row.type==1">天选之人</div>
            <div v-if="scope.row.type==2">无限盲盒</div>
            <div v-if="scope.row.type==3">寻宝</div>
            <div v-if="scope.row.type==4">能量球</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="获得规则">
          <template slot-scope="scope">
            <div v-if="scope.row.obtain==0">-</div>
            <div v-if="scope.row.obtain==1">购买可得</div>
            <div v-if="scope.row.obtain==2">规则可得</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="bz" label="备注"></el-table-column>
        <el-table-column align="center" prop="add_time" label="添加时间"></el-table-column>
        <el-table-column align="center" prop="update_time" label="更新时间"></el-table-column>
        <el-table-column align="center" prop="sort" label="排序"></el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button @click="handleEdite(scope.row)" type="text" size="small">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="margin-left:50px">
        <el-form-item label="赏级名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入赏级名称"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" prop="img">
          <el-upload
            class="avatar-uploader"
            action="https://upload-z0.qiniup.com/"
            :data="postData"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="盲盒类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择盲盒类型">
            <el-option label="天选之人" value="1"></el-option>
            <el-option label="无限盲盒" value="2"></el-option>
            <el-option label="寻宝" value="3"></el-option>
            <el-option label="能量球" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="获得类型" prop="obtain">
          <el-select
            v-model="form.obtain"
            placeholder="请选择获得类型"
            :disabled="form.type!=1&&form.type!=3"
          >
            <el-option label="购买可得" value="1"></el-option>
            <el-option label="规则可得" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.bz" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确定</el-button>
          <el-button @click="subCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { getToken } from '@/api/qiniu'
import { rewardList, addReward, editeReward } from '@/api/system'
import { parseTime } from '@/utils/index'

export default {
  name: 'Reward',
  data() {
    return {
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      //query
      query: {
        keywords: '',
        type: '0'
      },
      tableData: [],
      // 编辑抽屉
      drawer: false,
      direction: 'rtl',
      title: '编辑',
      form: {
        name: '',
        img: '',
        type: '',
        obtain: '',
        sort: '',
        bz: ''
      },
      rules: {
        name: [{ required: true, message: '请输入赏级名称', trigger: 'blur' }],
        img: [{ required: true, message: '请选择图片', trigger: 'blur' }],
        obtain: [
          { required: true, message: '请选输入获得类型', trigger: 'blur' }
        ],
        type: [{ required: true, message: '请选择盲盒类型', trigger: 'blur' }],
        sort: [{ required: true, message: '请选输入排序', trigger: 'blur' }]
      },
      // 上传图片
      url: '',
      imageUrl: '',
      postData: {
        token: ''
      },
      loading: false
    }
  },
  mounted() {
    this.getRewardList()
    this.getToken()
  },
  methods: {
    // 获取中将赏级列表
    async getRewardList() {
      this.loading = true
      const res = await rewardList({
        page: this.currentPage,
        limit: this.pageSize,
        keywords: this.query.keywords,
        type: this.query.type
      })
      this.loading = false
      console.log(res)
      this.total = res.count
      this.tableData = res.data
      this.tableData.forEach((item) => {
        if (item.add_time == 0) {
          item.add_time = '-'
        } else {
          item.add_time = parseTime(item.add_time, '{y}-{m}-{d} {h}:{i}:{s}')
        }
        if (item.update_time == 0) {
          item.update_time = '-'
        } else {
          item.update_time = parseTime(
            item.update_time,
            '{y}-{m}-{d} {h}:{i}:{s}'
          )
        }
      })
    },
    // 搜索列表
    queryAsk() {
      console.log(this.query)
      this.currentPage = 1
      this.getRewardList()
    },
    queryReset() {
      this.resetForm('query')
      this.total = 0
      this.currentPage = 1
      this.pageSize = 10
      this.query.keywords = ''
      this.query.type = '0'
      this.getRewardList()
    },
    addList() {
      this.drawer = true
      this.title = '添加'
    },
    handleEdite(row) {
      this.drawer = true
      this.title = '编辑'
      const form = {
        name: row.name,
        img: row.img,
        type: row.type,
        obtain: row.obtain,
        sort: row.sort,
        bz: row.bz
      }
      this.imageUrl = row.img
      this.form = form
      this.form.id = row.id
    },
    //分页改变
    currentChange(current) {
      this.currentPage = current
      this.getRewardList()
    },
    //抽屉
    handleClose(done) {
      this.resetForm('form')
      const form = {
        name: '',
        img: '',
        type: '',
        obtain: '',
        sort: '',
        bz: ''
      }
      this.imageUrl = ''
      this.form = form
      this.drawer = false
      done()
    },
    subCancel() {
      this.resetForm('form')
      const form = {
        name: '',
        img: '',
        type: '',
        obtain: '',
        sort: '',
        bz: ''
      }
      this.imageUrl = ''
      this.form = form
      this.drawer = false
    },
    onSubmit() {
      // 如果是无限盲盒obtain传0
      if (this.form.type == 2) {
        this.form.obtain = 0
      }

      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          if (this.title === '添加') {
            console.log(this.form)
            const res = await addReward({ ...this.form })
            console.log(res)
            if (res.st === 1) {
              this.resetForm('form')
              const form = {
                name: '',
                img: '',
                type: '',
                obtain: '',
                sort: '',
                bz: ''
              }
              this.imageUrl = ''
              this.form = form
              this.getRewardList()
              this.$message({
                message: '添加赏级成功',
                type: 'success'
              })
              this.drawer = false
            } else {
              console.log(res)
              this.$message.error('添加失败')
            }
          } else if (this.title === '编辑') {
            const res = await editeReward({ ...this.form })
            console.log(res)
            if (res.st === 1) {
              this.resetForm('form')
              const form = {
                name: '',
                img: '',
                type: '',
                obtain: '',
                sort: '',
                bz: '',
                id: ''
              }
              this.imageUrl = ''
              this.form = form
              this.getRewardList()
              this.$message({
                message: '编辑赏级成功',
                type: 'success'
              })
              this.drawer = false
            } else {
              console.log(res)
              this.$message.error('编辑失败')
            }
          }
        }
      })
    },
    // 上传图片
    async getToken() {
      const res = await getToken()
      this.postData.token = res.data.uptoken
      this.url = res.data.domain
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = this.url + res.key
      this.form.img = this.imageUrl
    },
    beforeAvatarUpload(file) {
      //   const isJPG = file.type === "image/jpeg";
      //   if (!isJPG) {
      //     this.$message.error("上传头像图片只能是 JPG 格式!");
      //   }
      const isLt1M = file.size / 1024 / 1024 < 1

      if (!isLt1M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
        return
      }
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.query-card {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  ::v-deep .el-form {
    display: flex;
  }
}
.box-card {
  margin-bottom: 20px;
}
.search {
  display: flex;
  align-items: center;
}
::v-deep .el-input--medium .el-input__inner {
  width: 360px;
}
::v-deep .el-textarea__inner {
  width: 360px;
}
::v-deep .el-drawer.rtl {
  width: 650px !important;
  overflow: auto;
}
// 上传图片
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>